<template>
  <div class="home">
    <el-row :gutter="20">

      <el-col :span="8">
        <el-card shadow="hover" style="height: 320px;box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);">
          <table style="width: 100%;height: 275px; border-collapse: collapse; font-family: Arial, sans-serif;">
            <tbody>
              <tr>
                <td style="text-align: left;">
                  快捷入口
                </td>
              </tr>
              <tr>
                <td style="text-align: left;" @click="goto('/main/Pinv/Po')" tabindex="-1"><svg-icon iconName="icon-gouwuche-copy"></svg-icon>
                  采购订单</td>
                <td style="text-align: left;" @click="goto('/main/Pinv/Pb')" tabindex="-1"><svg-icon iconName="icon-caigouruku1"></svg-icon>
                  采购入库</td>
              </tr>
              <tr>
                <td style="text-align: left;" @click="goto('/main/Pinv/Pu')" tabindex="-1"><svg-icon iconName="icon-caigoutuihuodan"></svg-icon>
                  采购退货</td>
                <td style="text-align: left;" @click="goto('/main/FG/Picking')" tabindex="-1"><svg-icon iconName="icon-lingliaochuku"></svg-icon>
                  领料出库</td>
              </tr>
              <tr>
                <td style="text-align: left;" @click="goto('/main/FG/FinishedGoodsStore')" tabindex="-1"><svg-icon iconName="icon-chengpinruku"></svg-icon>
                  成品入库</td>
                <td style="text-align: left;" @click="goto('/main/Inv/InvQty')" tabindex="-1"><svg-icon iconName="icon-kucunpandian"></svg-icon>
                  库存盘点</td>
              </tr>
              <tr>
                <td style="text-align: left;" @click="goto('/main/Sinv/SalesOrder')"tabindex="-1"><svg-icon iconName="icon-changongxiao_xiaoshoudingdan"></svg-icon>
                  销售订单</td>
                <td style="text-align: left;" @click="goto('/main/Sinv/SalesOutbound')" tabindex="-1"><svg-icon iconName="icon-a-xiaoshouchuku3"></svg-icon>
                  销售出库</td>
              </tr>
            </tbody>
          </table>
        </el-card>
      </el-col>

      <el-col :span="16">
        <el-card style="width: 100%; height: 320px; margin-bottom: 20px">
          <div ref="lineChart" style="width: 100%; height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <div class="section">
    <div class="total_qty">
      <div class="qty-title">业务单据数量</div>
      <div class="qty-value">{{ total_qty }}<span>单</span></div>
    </div>
    <div class="total_qty">
      <div class="qty-title">产品种类</div>
      <div class="qty-value">{{ pro_qty }}<span>种</span></div>
    </div>
    <div class="total_qty">
      <div class="qty-title">总入库数量</div>
      <div class="qty-value">{{ store_qty }}<span>件</span></div>
    </div>
    <div class="total_qty">
      <div class="qty-title">总出库数量</div>
      <div class="qty-value">{{ outbound_qty }}<span>件</span></div>
    </div>
    <div class="total_qty">
      <div class="qty-title">总退货数量</div>
      <div class="qty-value">{{ return_qty }}<span>件</span></div>
    </div>
  </div>

  <div class="section">
    <el-menu mode="horizontal" :default-active="activeMenu" @select="handleMenuSelect" class="inventory-menu">
      <el-menu-item index="purchaseOrderSummary">采购订单汇总</el-menu-item>
      <el-menu-item index="salesOrderSummary">销售订单汇总</el-menu-item>
    </el-menu>
    <component :is="currentComponent" :key="activeMenu" />
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from "echarts";
import purchaseOrderSummary from './SystemHomePage_purchaseOrderSummary.vue'
import salesOrderSummary from './SystemHomePage_salesOrderSummary.vue'
import axios from 'axios';
import { useRouter } from 'vue-router';
export default {
  setup() {
    const lineChart = ref(null);
    let chartInstance = null;
    const activeMenu = ref('purchaseOrderSummary')
    const total_qty = ref(0)
    const pro_qty = ref(0)
    const store_qty = ref(0)
    const outbound_qty = ref(0)
    const return_qty = ref(0)
    const finishedGoodsStoreList = ref([]);
    const router = useRouter()

    const initLineChart = () => {
      if (!lineChart.value) return;
      chartInstance = echarts.init(lineChart.value);

      const option = {
        title: {
          text: "成品入库统计",
          x: "center",
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}件'
        },
        grid: {
          top: 50,
          left: 50,
          right: 30,
          bottom: 30
        },
        xAxis: {
          type: "category",
          axisLabel: { rotate: 45 },
          data: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
        },
        yAxis: {
          name: "入库量(件)",
          type: "value",
          nameTextStyle: {
            padding: [0, 40, 0, 0] // 调整位置
          }
        },
        series: [{
          name: "实际入库量",
          type: "line",
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#1890ff' // 更醒目的蓝色
          },
          data: []
        }]
      };

      chartInstance.setOption(option);
    };

    const handleResize = () => {
      if (chartInstance) {
        chartInstance.resize();
      }
    };

    onMounted(() => {
      documentTotalNumber()
      proNumber()
      sotreNumber()
      outboundNumber()
      returnNumber()
      fetchFinishedGoodsStoreData()
      initLineChart();
      window.addEventListener('resize', handleResize);
      const resizeObserver = new ResizeObserver(() => {
        handleResize();
        // 窗口变化时重新统计数据
        if (finishedGoodsStoreList.value.length > 0) {
          updateLineChart(finishedGoodsStoreList.value);
        }
      });
      resizeObserver.observe(lineChart.value);
    });

    onUnmounted(() => {
      if (chartInstance) {
        chartInstance.dispose();
      }
      window.removeEventListener('resize', handleResize);
    });

    const menuComponentMap = {
      purchaseOrderSummary: purchaseOrderSummary,
      salesOrderSummary: salesOrderSummary,
    };

    const currentComponent = ref(menuComponentMap.purchaseOrderSummary);

    const handleMenuSelect = (index) => {
      activeMenu.value = index;
      currentComponent.value = menuComponentMap[index] || menuComponentMap.purchaseOrderSummary;
    };

    //查询业务单总数
    function documentTotalNumber() {
      axios.get("http://localhost:5181/api/SystemHome/GetBusinessCounts")
        .then((result) => {
          total_qty.value = result.data
        }).catch((err) => {
          console.info(err)
        });
    }

    //查询产品类别总数
    function proNumber() {
      axios.get("http://localhost:5181/api/Db_Product/ProductCount", {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        pro_qty.value = result.data
      }).catch((err) => {
        console.info(err)
      });
    }

    //查询入库总数
    function sotreNumber() {
      axios.get("http://localhost:5181/api/SystemHome/GetStoreCounts")
        .then((result) => {
          store_qty.value = result.data
        }).catch((err) => {
          console.info(err)
        });
    }

    //查询出库总数
    function outboundNumber() {
      axios.get("http://localhost:5181/api/SystemHome/GetOutboundCounts")
        .then((result) => {
          outbound_qty.value = result.data
        }).catch((err) => {
          console.info(err)
        });
    }

    //查询退货总数
    function returnNumber() {
      axios.get("http://localhost:5181/api/SystemHome/GetReturnCounts")
        .then((result) => {
          return_qty.value = result.data
        }).catch((err) => {
          console.info(err)
        });
    }

    // 获取成品入库数据
    function fetchFinishedGoodsStoreData() {
      axios.get("http://localhost:5181/api/FG_Finished_Goods_Store/Get_Finished_Goods_Store_Infos", {
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
      }).then((result) => {
        finishedGoodsStoreList.value = result.data;
        console.info(finishedGoodsStoreList.value)
        updateLineChart(result.data); // 更新折线图数据
      }).catch(console.error);
    }

    function updateLineChart(storeData) {
      if (!chartInstance) return;

      const monthlyData = aggregateMonthlyData(storeData);

      // 关键修复：计算动态Y轴范围
      const maxValue = Math.max(...monthlyData, 1); // 确保最小值为1
      const minValue = Math.min(...monthlyData, 0);

      chartInstance.setOption({
        yAxis: {
          min: minValue > 10 ? minValue * 0.8 : 0, // 留出20%底部空间
          max: maxValue * 1.2 // 上浮20%留出视觉空间
        },
        series: [{
          name: "实际",
          data: monthlyData,
          // 增加标签显示
          label: {
            show: true,
            position: 'top',
            formatter: '{c}件'
          }
        }]
      });

      // 打印最终配置验证
      console.log("生效配置:", {
        yAxis: chartInstance.getOption().yAxis[0],
        data: monthlyData
      });
    }

    function aggregateMonthlyData(storeData, year = new Date().getFullYear()) {
      const monthlyData = Array(12).fill(0);

      storeData.forEach(store => {
        try {
          const date = new Date(store.finished_goods_store_time);
          // 验证日期有效性
          if (isNaN(date)) throw new Error("日期解析失败");

          if (date.getFullYear() === year) {
            const month = date.getMonth();
            store.details.forEach(detail => {
              // 确保入库数量为数字
              const qty = Number(detail.store_qty);
              if (!isNaN(qty)) monthlyData[month] += qty;
            });
          }
        } catch (e) {
          console.error("数据处理异常:", e, store);
        }
      });
      console.log("月度聚合结果:", monthlyData); // 调试输出
      return monthlyData;
    }

    const goto = (path) =>{
      router.push(path)
    }

    // 日期格式化函数
    // function formatDate(dateString) {
    //   return new Date(dateString).toLocaleDateString();
    // }

    return {
      lineChart, currentComponent, handleMenuSelect, menuComponentMap, activeMenu, total_qty, pro_qty, store_qty, outbound_qty, return_qty,
      chartInstance,goto
    };
  }
}
</script>

<style scoped>
/* 去除表格单元格点击时的光标和焦点样式 */
.el-card table td {
  /* 禁止文本选择，避免光标出现 */
  user-select: none;
  -webkit-user-select: none;
  /* 阻止元素获得焦点 */
  pointer-events: auto; /* 保持点击事件可用 */
}

/* 去除单元格可能的焦点轮廓 */
.el-card table td:focus {
  outline: none !important;
  caret-color: transparent !important;
}
/* 针对包含点击事件的单元格进一步处理 */
/* .el-card table td[click]{
  cursor: pointer; 
} */

.home {
  width: 100%;
  height: 50%;

  .el-card {
    margin-bottom: 20px;
  }

  #line {
    width: 100%;
    height: 300px;
  }
}

/* ::v-deep .cell{
  background-color: yellow;
} */

.quick-access {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section {
  padding: 20px;
  margin: 30px 0px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  /* 添加阴影效果 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.total_qty {
  width: 225px;
  height: 125px;
  background-color: #f7fbff;
  display: inline-block;
  margin: 0 10px;

  position: relative;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  border-radius: 4px;
  overflow: hidden;
  box-sizing: border-box;
}

.total_qty:hover {
  box-shadow: 12px 12px 10px 0 #f7fbff !important;
}

.qty-title {
  color: #000;
  /* 黑色标题 */
  font-size: 18px;
  font-weight: 600;
  margin: 20px 0px;
}

.qty-value {
  color: #3366CC;
  /* 使用类似图片的蓝色 */
  font-size: 36px;
  font-weight: bold;
}

.qty-value span {
  color: #3366CC;
  font-size: 18px;
  margin-left: 4px;
}


/* 基础禁止选择规则 */
.el-card table td,
.total_qty,
.inventory-menu .el-menu-item {
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

/* 针对SVG图标单独处理 */
.el-card table td svg {
  user-select: none;
  pointer-events: auto;
}
/* 表格单元格焦点处理 */
.el-card table td:focus {
  outline: none !important;
  caret-color: transparent !important;
}

/* 菜单焦点处理 */
.inventory-menu .el-menu-item:focus {
  outline: none !important;
  box-shadow: none !important;
}

/* 数据块焦点处理 */
.total_qty:focus {
  outline: none !important;
}
/* 全局禁用点击高亮 */
* {
  -webkit-tap-highlight-color: transparent;
}

/* 数据块点击反馈优化 */
.total_qty:active {
  background-color: #e6f3ff;
  transform: scale(0.98);
  transition: all 0.1s ease;
}
.el-card table td,
.el-card table td * {
  user-select: none !important;
  -webkit-user-select: none !important;
  -moz-user-select: none !important;
  -ms-user-select: none !important;
}

.el-card table td:focus {
  outline: none !important;
  caret-color: transparent !important;
}

::v-deep .el-card__body,
::v-deep .el-card__body * {
  user-select: none !important;        /* 标准语法 */
  -webkit-user-select: none !important; /* Safari/Chrome */
  -moz-user-select: none !important;    /* Firefox */
  -ms-user-select: none !important;     /* IE/Edge */
}
</style>